const config = require("../config");
const md5 = require("md5.min.js");

const formatTime = date => {
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const day = date.getDate()
      const hour = date.getHours()
      const minute = date.getMinutes()
      const second = date.getSeconds()

      return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
      n = n.toString()
      return n[1] ? n : '0' + n
}



// ==============================================================================================================================
// ==============================================================================================================================
// ==============================================================================================================================
// ==============================================================================================================================
// ==============================================================================================================================
// ==============================================================================================================================

const baseConfig = {
      key: 'MNRBZ-V5JW2-7FTUG-CODUV-XL426-JCBMX'
}

//   本接口提供由地址描述到所述位置坐标的转换，与逆地址解析的过程正好相反。
function v1(data) {
      ajax({
            location: data['location']
      }, {
            url: 'https://apis.map.qq.com/ws/geocoder/v1/',
            success(res) {
                  !data['success'] || data['success'](res);
            }
      })
}

//   用于获取输入关键字的补完与提示，帮助用户快速输入。本接口为纯HTTP数据接口，需配合前端程序实现Autocomplete（自动完成）的效果。
function suggestion(data) {
      ajax({
            keyword: data['keyword'],
            region: data['region'],
      }, {
            url: 'https://apis.map.qq.com/ws/place/v1/suggestion',
            success(res) {
                  !data['success'] || data['success'](res);
            }
      })
}

// 指定城市的地点搜索：如在北京搜索餐馆；
function search(data) {
      ajax({
            // keyword: '海淀西大街',
            // boundary: "region('北京', 1)"
            keyword: data['keyword'],
            boundary: data['boundary'],
      }, {
            url: 'https://apis.map.qq.com/ws/place/v1/search',
            success(res) {
                  !data['success'] || data['success'](res);
            }
      })
}


function ajax(ajaxData, ajaxObj) {
      let defaultAjaxData = {
            key: 'MNRBZ-V5JW2-7FTUG-CODUV-XL426-JCBMX'
      }
      Object.assign(defaultAjaxData, ajaxData)
      let defaultConfig = {
            url: '',
            method: 'GET',
            data: defaultAjaxData,
            dataType: 'json',
            success(res) {
                  console.log(res)
            }
      }
      Object.assign(defaultConfig, ajaxObj)
      wx.request(defaultConfig)
}

function $ajax(ajaxData, ajaxObj, other) {
      !!other || (other = {})
      let guid = genGuid(),
            AppKey = other.AppKey || config['baseConfig'].AppKey
      if (!AppKey && !other.isAnony) {
            //如果 AppKey 不存在则跳出请求
            console.error(new Error('Ajax 发送服务器请求: AppKey 不存在, 发送服务器网络失败'))
            return;
      }

      if (other.reqJson) {
            !!ajaxObj.header || (ajaxObj.header = {})
            ajaxObj.header["content-type"] = "application/json; charset=utf-8"
            ajaxData = JSON.stringify(ajaxData)
      }

      let initData = {
            timestamp: new Date().getTime()
      };
      !AppKey || (initData.app_key = AppKey)
      let headerData = Object.assign({}, initData) //用于添加到 header
      if (other.ajaxHeader !== null && typeof other.ajaxHeader === "object") {
            Object.assign(headerData, other.ajaxHeader)
      }

      if (!other.noSign && !!ajaxData && !other.reqJson && ((!!ajaxObj["contentType"] && !ajaxObj["contentType"].includes("application/json")) || (ajaxObj['method'] !== 'post'))) {
            Object.assign(initData, ajaxData) //用于生成 sign
      }


      let options = {
            method: 'post',
            dataType: 'json',
            timeout: 10000,
            header: Object.assign({
                  instance_id: genGuid(),
                  DataTag: guid
            }, headerData),
            data: ajaxData,
      };
      other.noSign || (options.header.sign = getSign(initData, other.AppSecret))
      Object.assign(options, ajaxObj)
      wx.request(options)
}

function genGuid() {
      //生成 网络请求 Id
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            let r = Math.random() * 16 | 0,
                  v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16); //16进制
      });
}

function getSign(obj, appSecret) {
      //生成ajax Sign
      !!appSecret || (appSecret = config['baseConfig'].AppSecret)
      let signstr = appSecret + objKeySorttoStr(obj) + appSecret
      return md5(signstr).toUpperCase();
}

function objKeySorttoStr(obj) { //排序函数
      let newkey = Object.keys(obj).sort(function (a, b) {
            let aLower = a.toLowerCase(),
                  bLower = b.toLowerCase()
            if (aLower < bLower) return -1;
            if (aLower > bLower) return 1;
            if (aLower == bLower) {
                  return a > b ? -1 : 1
            }
            return 0;
      });
      //先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，newkey是一个数组
      let newStr = ''; //创建一个字符串变量，用于存放排好序的键值对
      for (let i = 0; i < newkey.length; i++) { //遍历newkey数组
            newStr += newkey[i] + obj[newkey[i]]
      }
      return newStr; //返回排好序拼接成的字符串
}

module.exports = {
      formatTime: formatTime,
      search: search,
      suggestion: suggestion,
      v1: v1,
      $ajax: $ajax,
}